/*
 * @Author: liuying 247220246@qq.com
 * @Date: 2025-04-02 17:54:02
 * @LastEditors: liuying 247220246@qq.com
 * @LastEditTime: 2025-04-14 15:35:23
 * @FilePath: \my-book-react\src\stores\createReducerManager.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { combineReducers, AnyAction, Reducer } from '@reduxjs/toolkit';
import { IReducers } from '@/stores/configStore';

// 创建一个reducer管理器
const createReducerManager = (initialReducers: IReducers) => {
  // 初始化reducers
  let reducers = { ...initialReducers };
  // 将reducers合并为一个rootReducers
  let rootReducers = combineReducers(reducers);
  // 定义一个数组，用于存储要删除的reducer的key
  let keysToRemove: Array<string> = [];
  // 返回一个对象，包含getReducers、reduce、addReduvers、removeReducers四个方法
  return {
    // 获取reducers
    getReducers: () => reducers,
    // 执行reducer
    reduce: (state: any, action: AnyAction) => {
      // 定义一个新的state
      let newState = state;
      // 如果有要删除的reducer，则删除
      if (keysToRemove.length > 0) {
        newState = {
          ...state,
        };
        for (let key of keysToRemove) {
          delete newState[key];
        }
        keysToRemove = [];
      }
      // 返回rootReducers
      return rootReducers(state, action);
    },
    // 添加新的reducers
    addReducers: (newReducers: IReducers) => {
      // 遍历新的reducers
      Object.keys(newReducers).forEach((key: string) => {
        // 如果key不存在或者reducers中不存在该key，则添加
        if (!key || !reducers[key]) {
          reducers[key] = newReducers[key];
        }
      });
      // 重新合并reducers
      rootReducers = combineReducers(reducers);
    },
    // 删除reducers
    removeReducers: (keys: string[]) => {
      // 遍历要删除的keys
      keys.forEach((key: string) => {
        // 如果key存在且reducers中存在该key，则删除
        if (keys && reducers[key]) {
          delete reducers[key];
          keysToRemove.push(key);
        }
      });
      // 重新合并reducers
      rootReducers = combineReducers(reducers);
    },
  };
};
export default createReducerManager;
